﻿using Rabbit.Common;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Rabbit.Consumer.Helloword
{
    ////Helloword接收  基本模型
    internal class ReceiveHelloword
    {
        ///// <summary>
        ///// 接收消费
        ///// </summary>
        //public static async void ReceiveHellowordMsg()
        //{
        //    string qName = "HwQue";//队列名称
        //    //创建连接
        //    using var connection = await RabbitMQHelper.GetConnect();
        //    //创建信道
        //    using var channel = await connection.CreateChannelAsync();

        //    //创建队列 如果先启动消费者，且又不创建队列，程序异常
        //    await channel.QueueDeclareAsync(queue: qName, durable: false, exclusive: false, autoDelete: false, arguments: null);

        //    var consumer = new AsyncEventingBasicConsumer(channel);//消费者


        //    consumer.ReceivedAsync += (model, e) =>
        //    {
        //        //二进制流转字符串 (Encoding.UTF8.GetString 方法是用于将UTF-8编码的字节数组转换为一个字符串的方法。)
        //        string msg = Encoding.UTF8.GetString(e.Body.ToArray());
        //        Console.WriteLine("已经消费了消息 "+msg);


        //        // 处理消息...
        //        AsyncEventingBasicConsumer cons = (AsyncEventingBasicConsumer)model;
        //        IChannel ch = cons.Channel;

        //        ch.BasicAckAsync(deliveryTag:e.DeliveryTag, multiple:true);//手动签收 批量


        //        return Task.CompletedTask;//已完成任务
        //    };

        //    await channel.BasicConsumeAsync(qName, autoAck: false, consumer: consumer);//自动消费 签收

        /// <summary>
        /// 接收消息
        /// </summary>
        public static void ReceiveHellowordMsg()
        {
            string qName = "HwQue";//队列名称
            //创建连接
            var conn = RabbitMQHelper.GetConnect();
            //创建信道
            var channel = conn.CreateModel();
            //创建队列 如果先启动消费者，且又不创建队列，程序异常
            channel.QueueDeclare(qName, false, false, false, null);

            var consumer = new EventingBasicConsumer(channel);//消费者
            consumer.Received += (m, e) =>
            {
                //业务处理

                //二进制流转字符串 (Encoding.UTF8.GetString 方法是用于将UTF-8编码的字节数组转换为一个字符串的方法。)
                string msg = Encoding.UTF8.GetString(e.Body.ToArray());
                Console.WriteLine("已经消费了消息:" + msg);

                //channel.BasicAck(e.DeliveryTag,multiple: true);//手动签收 multiple：是否批量签收

                //拒收
                channel.BasicReject(e.DeliveryTag, requeue: false);//拒收。 requeue 是否返回原队列(true:回原队列)(配合死信队列)
            
            };

            //慎用自动签收
            channel.BasicConsume(queue: qName, autoAck: false, consumer);//自动签收 (autoAck:true)

        }



    }
        
       
}
